<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Util\UploadFile;

/**
 * 单位信息管理
 * Class HouseController
 * @package Admin\Controller
 */
class HouseController extends BaseController {

    static $houseType = array('保障性住房', '直管公房', "商业用房");

    /**
     * 系统管理 -> 系统管理 -> 建筑物信息维护 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出小区信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("house")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //设置community building信息
        $this->assign("community", $this->fn_GetCommunityDict());
        $this->assign("building", $this->fn_GetBuildingDict());
        $this->assign("type", array(0=>"廉租房", 1=>"公租房"));

        //设置搜索条件
        $this->assign("filter", $filter);
        $years = $this->fn_GenerateYears(2015, date("Y"));
        $years2 = array_reverse($years);
        $this->assign("years", $years);
        $this->assign("years2", $years2);

        $this->display();
    }

    private function fn_GenerateYears($from, $end){
        $res = array();
        for($i=$from; $i<=$end; $i++){
            $res[] = $i;
        }
        return $res;
    }

    /**
     * 获取房源的租赁日志，只取最近5条
     * $houseId: 房源ID
     */
    protected function fn_GetRentalLog($houseId){
        $where = array("house_no"=>$houseId);
        return M("house_log")->where($where)->order("id desc")->limit(5)->select();
    }

    /**
     * 获取房源的维修记录
     * $houseId: 房源ID
     */
    protected function fn_GetRepairLog($houseId){
        $where = array("house_id"=>$houseId);
        return M("repair")->where($where)->order("id desc")->limit(5)->select();
    }

    public function ajax_GetBuildingByCommunity(){
        $res = $this->fn_GetBuildingList(I("post.cid"));
        $this->ajaxReturn($res);
    }

    private function fn_GetCommunityList(){
        return M("community")->where()->select();
    }

    private function fn_GetCommunityDict(){
        $community = array();
        $list = M("community")->where()->select();
        for($i=0; $i<count($list); $i++){
            $community[$list[$i]["id"]] = $list[$i]["name"];
        }
        return $community;
    }

    /**
     * 通过小区ID来获取相关建筑物信息
     * @param $cid
     * @return mixed
     */
    private function fn_GetBuildingList($cid){
        $where = array("community_id"=>$cid);
        return M("building")->where($where)->select();
    }

    private function fn_GetBuildingDict($cid=null){
        if($cid){
            $where = array("community_id"=>$cid);
        }else{
            $where = array();
        }
        $building = array();
        $list = M("building")->where($where)->select();
        for($i=0; $i<count($list); $i++){
            $building[$list[$i]["id"]] = $list[$i]["name"];
        }
        return $building;
    }

    public function import(){
        if(IS_POST){
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize  = 314572811 ;// 设置附件上传大小
            $upload->allowExts  = array('xls', 'xlsx');// 设置附件上传类型
            $upload->savePath =  './Public/UPLOADS/';// 设置附件上传目录
            $info = $upload->uploadOne($_FILES["excel"]);

            if ($info['state']) {
                $newFile = $upload->savePath . $info["info"]['savename'];
                $this->fn_ImportTaizhangExcel($newFile);
                $this->error("恭喜您，数据导入成功");
            }else{
                $this->error($info["msg"]);
            }
        }
        $this->display();
    }

    /**
     * 导出台账，导出规则：
     * 1.如果选中了某些行，则导出所选中的项；
     * 2.如果没有选中任意行，则导出所有的项；
     */
    public function export(){
        $where = array();
        $ids = I("get.ids");
        if($ids){
            $where = "id in (".$ids.")'";
        }else if(I("get.field") & I("get.value")){
            $where[I("get.field")] = array("like", "%".I("get.value")."%");
        }
        $this->assign("year1", I("get.year1"));
        $this->assign("year2", I("get.year2"));
        $this->assign("type", I("get.type"));
        $this->assign("where", serialize($where));
        $this->display();
    }

    public function ajax_export(){
        set_time_limit(0);
        if(I("post.type")=="house"){
            $this->action_ExportHouse();
        }else if(I("post.type")=="shenji"){
            $this->action_ExportShenji(intval(I("post.year1")), intval(I("post.year2")));
        }
        $this->error("请选择导出数据类型");
    }

    public function action_ExportShenji($year1, $year2){

        import("Common.ORG.Util.PHPExcel");
        import("Common.ORG.Util.PHPExcel.Writer.Excel5");
        import("Common.ORG.Util.PHPExcel.IOFactory.php");

        $inputFileName = "./db/xlsx_tpl/shenji.xls";
        try { //  Read your Excel workbook
            $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        }

        if($year2-$year1>6){
            $this->error("最多只能导出6年的审计数据");
        }

        //设置表格的头，
        $objPHPExcel->setActiveSheetIndex(0);
        $offset = 0;
        $cell = array("P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA");
        for($i=0; $i<=($year2-$year1)*2; $i+=2){
            $objPHPExcel->getActiveSheet()->SetCellValue($cell[$i].'2', " ".($year1+$offset)."年已收租金");
            $objPHPExcel->getActiveSheet()->SetCellValue($cell[$i+1].'2', " ".($year1+$offset)."年已收租金期限");
            $offset += 1;
        }

        $rowCount = 3; //从第2行开始写数据
        $where = unserialize(I("post.where"));
        $total = M("house")->where($where)->count();
        $offset = 0;
        $pageNum = 100;
        $years = $this->fn_GenerateYears($year1, $year2);
        while($offset<$total){
            $data = M("house h")
                ->field("c.name as c_name, h.name, h.addr, h.size, zhname, zhidno, zhname2,
                 zhidno2, phone, jtnum, dibaohm, t.derate_type, dbnum, c.zj, price")
                ->join(C('DB_PREFIX')."community c on c.id=h.community_id", 'LEFT')
                ->join(C('DB_PREFIX')."contact t on t.no=h.contact_no", 'LEFT')
                ->where($where)
                ->limit($offset.",".$pageNum)
                ->select();

            //测试数据
            /*$data = array(
                array(
                    "c_name"=>'东正小区', "name"=>"0301-18603", "addr"=>"0101-01202",
                    "size"=>"0101-01202", "zhname"=>"0101-01202", "zhidno"=>"0101-01202",
                    "zhname2"=>"0101-01202", "zhidno2"=>"0101-01202", "phone"=>"15388094958",
                    "jtnum"=>"3", "dibaohm"=>"022121", "dbnum"=>3,
                    "zj"=>2, "price"=>100,
                ),
                array(
                    "c_name"=>'东正小区2', "name"=>"0301-18604", "addr"=>"0101-01202",
                    "size"=>"0101-01202", "zhname"=>"0101-01202", "zhidno"=>"0101-01202",
                    "zhname2"=>"0101-01202", "zhidno2"=>"0101-01202", "phone"=>"15388094958",
                    "jtnum"=>"3", "dibaohm"=>"022121", "dbnum"=>3,
                    "zj"=>2, "price"=>100,
                )
            );*/

            $hnos = array();
            foreach ($data as $item) {
                $hnos[] = $item['name'];
            }
            $rental = $this->fn_GetHouseRental($hnos, $years);
            for($i=0; $i<count($data); $i++){
                $dtype = "无";
                if($data[$i]['derate_type']=='1至6级军残全额减免'){
                    $dtype = '半免';
                }else if($data[$i]['derate_type']=='7级以上军残一半减免'){
                    $dtype = '全免';
                }
                $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, " ".$data[$i]["c_name"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, " ".$data[$i]["name"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, " ".$data[$i]["addr"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, " ".$data[$i]["size"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, " ".$data[$i]["zhname"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, " ".$data[$i]["zhidno"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount, " ".$data[$i]["zhname2"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('H'.$rowCount, " ".$data[$i]["zhidno2"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount, " ".$data[$i]["phone"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount, " ".$data[$i]["jtnum"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('K'.$rowCount, " ".$data[$i]["dibaohm"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount, " ".$data[$i]["dbnum"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount, " ".$data[$i]["zj"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('N'.$rowCount, " ".$data[$i]["price"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('O'.$rowCount, " ".$dtype);

                //设置租金信息
                $offset2 = 0;
                for($j=0; $j<=($year2-$year1)*2; $j+=2){
                    $amount = $rental[$data[$i]['name']][$year1+$offset2][0];
                    $qixain = $rental[$data[$i]['name']][$year1+$offset2][1];
                    $objPHPExcel->getActiveSheet()->SetCellValue($cell[$j].$rowCount, $amount);
                    $objPHPExcel->getActiveSheet()->SetCellValue($cell[$j+1].$rowCount, " ".$qixain);
                    $offset2 += 1;
                }
                $rowCount += 1;
            }
            $offset += $pageNum;
        }

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $newFile = '/db/export/'.time().'.xlsx';
        $objWriter->save(".".$newFile);
        $this->success($newFile);
    }

    /**
     * 返回结果示例
     * array(
     *  hno1 => array(
     *          "year1" => array(1, 2017.01-12),
     *          "year2" => array(1, 2017.01-12),
     *      ),
     *  hno2 => array(
     *          "year1" => array(1, 2017.01-12),
     *          "year2" => array(1, 2017.01-12),
     *      )
     * )
     * @param $hnos
     * @param $years
     * @return array
     */
    private function fn_GetHouseRental($hnos, $years){
        $res = array();
        foreach($hnos as $hno){
            $res[$hno] = array();
            foreach($years as $year){
                $res[$hno][$year] = array(0.00, "");
            }
        }
        $where = array("house_no"=>array("in", $hnos), "year"=>array("in", $years));
        $pays = M("payments")->field("dtype,house_no,year,month_start,month_end,amount")->where($where)->select();
        foreach($pays as $item){
            $qixian = $item['year'].".".$item['month_start']."-".$item['month_end'];
            $res[$item['house_no']][$item['year']] = array($item['amount'], $qixian);
        }
        return $res;
    }

    public function action_ExportHouse(){

        import("Common.ORG.Util.PHPExcel");
        import("Common.ORG.Util.PHPExcel.Writer.Excel5");
        import("Common.ORG.Util.PHPExcel.IOFactory.php");

        $inputFileName = "./db/xlsx_tpl/house.xls";
        try { //  Read your Excel workbook
            $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        }

        $objPHPExcel->setActiveSheetIndex(0);
        $rowCount = 3; //从第2行开始写数据
        $where = unserialize(I("post.where"));
        $total = M("house")->where($where)->count();
        $offset = 0;
        $pageNum = 100;
        while($offset<$total){
            $data = M("house h")
                ->field("h.name, h.size, h.dybh, h.addr, h.no, c.name as c_name, b.name as b_name")
                ->join(C('DB_PREFIX')."community c on c.id=h.community_id", 'LEFT')
                ->join(C('DB_PREFIX')."building b on b.id=h.building_id", 'LEFT')
                ->where($where)
                ->limit($offset.",".$pageNum)
                ->select();
            //$this->error(M()->getLastSql());
            for($i=0; $i<count($data); $i++){
                $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, " ".$data[$i]["c_name"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, " ".$data[$i]["b_name"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, " ".$data[$i]["dybh"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, " ".$data[$i]["no"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, " ".$data[$i]["name"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, " ".$data[$i]["addr"]);
                $objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount, " ".$data[$i]["size"]);
                $rowCount += 1;
            }

            $offset += $pageNum;
        }

        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $newFile = '/db/export/'.time().'.xlsx';
        $objWriter->save(".".$newFile);
        $this->success($newFile);
    }

    public function fn_ImportTaizhangExcel($inputFileName){
        import("Common.ORG.Util.PHPExcel");
        import("Common.ORG.Util.PHPExcel.Writer.Excel5");
        import("Common.ORG.Util.PHPExcel.IOFactory.php");

        set_time_limit(0);

        try { //  Read your Excel workbook
            $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        }

        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        //$this->error($highestColumn);



        $trans = M();
        $trans->startTrans();   // 开启事务
        try{


            $community = $this->fn_GetCommunityNameDict();
            for ($row = 3; $row <= $highestRow; $row++){
                $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                if(!array_key_exists($rowData[0][0], $community)){
                    $this->error("第".$row."行,小区名：".$rowData[0][0]."不存在");
                }
                if(!array_key_exists($rowData[0][1], $community[$rowData[0][0]]['buildings'])){
                    $this->error("第".$row."行,建筑物名称：".$rowData[0][1]."不存在");
                }
            }

            //  Loop through each row of the worksheet in turn
            // 第四行开始读取数据
            $fields = array("community_id", "building_id", "dybh", "no", "name", "addr", "size", "type");
            for ($row = 3; $row <= $highestRow; $row++){
                $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                $data = array();
                for($i=0; $i<count($fields); $i++){
                    if($fields[$i]=="community_id"){
                        $data["price"] = $community[$rowData[0][$i]]['zj'];
                        $data["mprice"] = $community[$rowData[0][$i]]['mzj'];
                        $data[$fields[$i]] = $community[$rowData[0][$i]]['id'];
                    }else if($fields[$i]=="building_id"){
                        $data[$fields[$i]] = $community[$rowData[0][0]]['buildings'][$rowData[0][$i]];
                    }else{
                        $data[$fields[$i]] = $rowData[0][$i];
                    }
                }
                if(!empty($data)){
                    $data["price"] = $data['price']*floatval($data['size']);
                    $data["mprice"] = $data['mprice']*floatval($data['size']);
                    $data["cuser"] = session("username");
                    $data["ctime"] = time();
                    if(!M("house")->add($data)){
                        $this->error(M("house")->getLastSql());
                        $this->error("数据导入失败，行数：".$row);
                    }
                }
            }

            $trans->commit();   // 提交事务
        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    protected function fn_GetCommunityNameDict(){
        $data = array();
        $comm = M("community")->select();
        foreach ($comm as $item) {
            $data[$item['name']] = array(
                "id" => $item['id'],
                "zj" => $item['zj'],
                "mzj" => $item['mzj'],
                "buildings" => $this->fn_GetBuildingNameDict($item['id']),
            );
        }
        return $data;
    }

    protected function fn_GetBuildingNameDict($commId){
        $data = array();
        $where = array("community_id"=>$commId);
        $comm = M("building")->where($where)->select();
        foreach ($comm as $item) {
            $data[$item['name']] = $item['id'];
        }
        return $data;
    }

    /**
     * 建筑物信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $house = M("house")->where(array("id"=>$dataId))->find();
        $this->assign("house", $house);

        //读取租赁，维修记录
        $this->assign("rental", $this->fn_GetRentalLog($house['name']));
        $this->assign("repair", $this->fn_GetRepairLog($dataId));

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);

        //设置community信息
        $options = $this->fn_GetCommunityList();
        $this->assign("community_options", json_encode ($options));
        $community = $this->fn_GetCommunityDict();
        $this->assign("community", $community);
        $options = $this->fn_GetBuildingList($house["community_id"]);
        $this->assign("building_options", json_encode($options));
        $building = $this->fn_GetBuildingDict($house["community_id"]);
        $this->assign("building", $building);

        $this->assign("type_options", json_encode(self::$houseType));
        $this->display();
    }

    /**
     * 建筑物信息维护 -> 新增
     */
    public function add(){  //todo
        if(IS_POST){    //添加小区信息
            $data = array(
                "community_id" => I("post.community_id"),
                "building_id" => I("post.building_id"),
                "name" => I("post.name"),
                "addr" => I("post.addr"),
                "dybh" => I("post.dybh"),
                "state" => "闲置中",
                //"price" => I("post.price"),
                //"mprice" => I("post.mprice"),
                "huxing" => I("post.huxing"),
                "direction" => I("post.direction"),
                "size" => I("post.size"),
                "remarks" => I("post.remarks"),
                "cuser" => session("username"),
                "ctime" => time()
            );

            //计算租金
            $comm = M("community")->where(array("id"=>$data['community_id']))->find();
            $data['price'] = floatval($comm['zj'])*floatval($data['size']);
            $data['mprice'] = floatval($comm['mzj'])*floatval($data['size']);

            $dataId = M("house")->add($data);
            if($dataId){
                header("Location:/admin/house/detail?id=".$dataId);
            }else{
                $this->error("系统错误，创建房源信息失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $house = M("house")->where(array("id"=>I("get.id")))->find();
            $this->assign("house", $house);

            $building = $this->fn_GetBuildingList($house["community_id"]);
            $this->assign("building", $building);
        }
        $this->assign("type", array(array(id=>"廉租房", name=>"廉租房"), array(id=>"公租房", name=>"公租房")));
        //设置community信息
        $this->assign("community", $this->fn_GetCommunityList());
        $this->assign("houseType", self::$houseType);
        $this->display();
    }

    public function ajax_UpdateNS(){
        $state = I("post.state");
        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $data = array("req_nianshen"=>$state);
        $map["id"] = array("in", $dataIds);
        M("house")->where($map)->save($data);
        $this->success("操作成功");
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $res = M("house")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $res = M("house")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("house")->where(array("id"=>$dataId))->save($data);
        if($res){
            $house = M("house")->where(array("id"=>$dataId))->find();
            $sync = array(
                "house_no"=>$house['name'],"house_addr"=>$house['addr'],
                "idno"=>$data['zhidno'],"phone"=>$data['phone'],"name"=>$data['zhname'],
            );
            $this->fn_SyncZhuhuInfo($sync);
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    public function fn_SyncZhuhuInfo($sync){
        //合同信息
        M("contact")->where(array("yifang"=>$sync['name'], "fwdz"=>$sync['house_addr']))
            ->save(array("yfsfz"=>$sync['idno'],"yfdh"=>$sync['phone']));
        M("charge")->where(array("name"=>$sync['name'], "house_addr"=>$sync['house_addr']))
            ->save(array("idno"=>$sync['idno'],"phone"=>$sync['phone']));
        M("payments")->where(array("payer"=>$sync['name'], "house_addr"=>$sync['house_addr']))
            ->save(array("payer_idno"=>$sync['idno']));
        M("prepay")->where(array("name"=>$sync['name'], "house_addr"=>$sync['house_addr']))
            ->save(array("idno"=>$sync['idno'],"phone"=>$sync['phone']));
        M("derate")->where(array("name"=>$sync['name'], "house_addr"=>$sync['house_addr']))
            ->save(array("idno"=>$sync['idno'],"phone"=>$sync['phone']));
        M("menmian")->where(array("name"=>$sync['name'], "house_addr"=>$sync['house_addr']))
            ->save(array("idno"=>$sync['idno'],"phone"=>$sync['phone']));
        M("lzf")->where(array("name"=>$sync['name'], "house_addr"=>$sync['house_addr']))
            ->save(array("idno"=>$sync['idno'],"phone"=>$sync['phone']));
        M("gzf")->where(array("name"=>$sync['name'], "house_addr"=>$sync['house_addr']))
            ->save(array("idno"=>$sync['idno'],"phone"=>$sync['phone']));
    }
    protected function fn_GetCommunity($username){
        $data = array();
        $where = array("admin_name"=>$username);
        $comm = M("community")->field("id")->where($where)->select();
        foreach ($comm as $item) {
            $data[] = $item['id'];
        }
        return $data;
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){

        $where = array();
        if($_REQUEST['where']){
            $where = unserialize($_REQUEST['where']);
        }

        if(self::$u["role_code"]=='20000'){ //小区管理员
            $com = $this->fn_GetCommunity(self::$u['username']);
            $where['community_id'] = array("in", $com);
        }

        if(I("request.value")){
            if(I("request.field")=="community_id"){ //多表查询处理
                $cateIds = $this->fn_SelectCommunityByName(I("request.value"));
				if($cateIds){
					$where[I("request.field")] = array("in", $cateIds);					
				}
            }else{
                $where[I("request.field")] = array("like", "%".I("request.value")."%");
            }
        }
        return $where;
    }

    private function fn_SelectCommunityByName($name){
        $where["name"] =  array("like", "%".$name."%");
        $result = M("community")->where($where)->field("id")->select();
        $cateIds = array();
        for($i=0; $i<count($result); $i++){
            array_push($cateIds, $result[$i]["id"]);
        }
        return $cateIds;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "where" => $_REQUEST["where"],
                "field" => I("post.field"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "where" => $_REQUEST["where"],
            "order_field" => "id",
            "order_sort" => "desc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "where" => $_REQUEST["where"],
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("house")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("house")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("house")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("house")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

}